package com.origin.chaos.security.util;

import com.origin.chaos.common.exception.NotLoginException;
import com.origin.chaos.security.bean.LoginUser;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户登录token相关的工具类
 *
 * @author: tao.ding
 * @date 2021-07-19
 */
public class TokenUtil {
    /**
     * 获取当前登录用户的登录token
     *
     * @return
     */
    public static String getCurrentLoginUserToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        if (ObjectUtils.isEmpty(token)) {
            throw new NotLoginException("用户未登录");
        }
        return token;
    }

    /**
     * 获取当前登录用户信息
     *
     * @return
     */
    public static LoginUser getCurrentLoginUser() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        LoginUser loginUser = (LoginUser) request.getAttribute(LoginUser.class.getName());
        if (null == loginUser) {
            throw new NotLoginException("用户未登录");
        }
        return loginUser;
    }

    /**
     * 确保用户登录了
     */
    public static void ensureLogin() {
        getCurrentLoginUser();
    }
}
